import {Component, OnInit} from '@angular/core';
import {Rpower} from '../../../entity/rpower.model';
import {ApplicationService} from '../../../service/application.service';
import {LossElectricityService, PowerType} from '../../../service/loss-electricity.service';
import {Farm} from '../../../entity/farm.model';
import {DatePipe} from '@angular/common';
import {TreeNode, ConfirmationService} from 'primeng/primeng';
// 表格导出为Excel
import * as XLSX from 'xlsx';

@Component({
  selector: 'app-r-power',
  templateUrl: './r-power.component.html',
  styleUrls: ['./r-power.component.css']
})
export class RPowerComponent implements OnInit {
  startTime = new Date(new Date().getTime() - 1000 * 60 * 60 * 24 * 1);
  endTime = new Date(new Date().getTime() - 1000 * 60 * 60 * 24);
  years: string[] = [];
  months: string[] = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'];
  endYear: string = this.startTime.getFullYear().toString();
  endMonth: string = this.months[this.startTime.getMonth()].toString();
  startYear: string = (this.startTime.getFullYear() - 1).toString();
  startMonth: string = this.months[this.startTime.getMonth()].toString();
  active = 0;
  rPowers: Rpower[] = [];
  fileOther: File;
  fileDayPower: File;
  file: File;
  fileSpeed: File;
  farms: Farm[] = [];
  selectFarmId: number;
  powerTypes = [];
  selectOptions: PowerType[] = [];
  selectedOption: number;
  powerCategorytag: number;
  cols: any[];
  firstDay = 0;
  firstMonth = 0;
  firstYear = 0;
  rows = 20;
  en = {
    firstDayOfWeek: 0,
    dayNames: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
    dayNamesShort: ['日', '一', '二', '三', '四', '五', '六'],
    dayNamesMin: ['日', '一', '二', '三', '四', '五', '六'],
    monthNames: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
    monthNamesShort: ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二'],
    today: '今天',
    clear: '清除'
  };
  private fomat: string = 'yyyy-MM-dd';
  rPowerMonths: Rpower[] = [];
  rPowerYears: Rpower[] = [];

  constructor(
    public application: ApplicationService,
    private lossElectricity: LossElectricityService,
    private datePipe: DatePipe,
    private confirmation: ConfirmationService,
  ) {
  }

  ngOnInit() {
    this.cols = [
      {field: 'date', header: '时间', width: '5%'},
      {field: 'plantName', header: '风场名称', width: '10%'},
      {field: 'genpow', header: '发电量(kWh)', width: '10%'},
      {field: 'pucspow', header: '网购电量（kWh）', width: '10%'},
      {field: 'ongrdpow', header: '上网电量（kWh）', width: '10%'},
    ];
    let year = new Date().getFullYear();
    this.years.push(year.toString());
    for (let i = 0; i <= 5; i++) {
      year--;
      this.years.push(year.toString());
    }
    this.onSearch();
    this.farms = this.application.currentUserFarms;
  }

  onClick(active: number) {
    this.active = active;
    // this.rPowers = [];
  }

  /* onRowSelect(event) {
    this.selectFarmId = this.selectedRPower.farmId;
    this.currentRpower = event.data;
    this.changeValue = event.data.value;
    this.displayDialog = true;
  } */
  onSearch() {
    let startTime = '', endTime = '', dateType = 1;
    if (this.active === 0) {
      dateType = 1;
      // if (this.startTime.getTime() > this.endTime.getTime()) {
      //   alert('开始时间不能大于结束时间');
      //   return false;
      // }
      startTime = this.datePipe.transform(this.startTime, this.fomat);
      // endTime = this.datePipe.transform(this.endTime, this.fomat);
      endTime = startTime;
    } else if (this.active === 1) {
      dateType = 2;
      startTime = `${this.startYear}-${this.startMonth}`;
      endTime = `${this.endYear}-${this.endMonth}`;
    } else if (this.active === 2) {
      dateType = 3;
      if (this.startYear > this.endYear) {
        alert('开始时间不能大于结束时间');
        return false;
      }
      startTime = `${this.startYear}`;
      endTime = `${this.endYear}`;
    }
    this.lossElectricity.getFarmPowerByTime(startTime, endTime, dateType).then(res => {
      if (res) {
        if (dateType == 1) {
          this.rPowers = [...res];
        } else if (dateType == 2) {
          this.rPowerMonths = [...res];
        } else if (dateType == 3) {
          this.rPowerYears = [...res];
        }
      }
    }).catch(err => {
      console.log(err);
    });
  }

  onImport() {
    this.lossElectricity.importBattery(this.file)
      .then(res => {
        if (res && res.code == '200') {
          alert('导入成功！');
          this.onSearch();
          this.onRemoveOther();
        } else {
          alert('导入失败');
        }
      })
      .catch(err => {
        alert('导入失败');
      });
  }

  onUpload(ev) {
    this.file = ev.files;
    this.onImport();

  }

  onExportDayPower() {
    let str = `<thead>
      <tr>
        <th>时间</th>
          <th>风场</th>
          <th>发电量(万kWh)</th>
          <th>网购电量（万kWh）</th>
          <th>上网电量（万kWh）</th>
          <th>平均风速（m/s）</th>
          <th>日最大出力</th>
      </tr>
    </thead>
    <tbody>`;
    this.rPowers.forEach(row => {
      str += `<tr >
          <td>${row.date}</td>
          <td>${row.plantName}</td>
          <td>${+row.genpow && +row.genpow.toFixed(5)}</td>
          <td>${+row.pucspow&& +row.pucspow.toFixed(5)}</td>
          <td>${+row.ongrdpow&& +row.ongrdpow.toFixed(5)}</td>
          <td>${+row.avgwdspd&& +row.avgwdspd.toFixed(3)}</td>
          <td>${+row.maxpow&& +row.maxpow.toFixed(3)}</td>
      </tr>`;
    })
    str += `</tbody>
  `;

    const elemTable = document.createElement('table');
    elemTable.innerHTML = str;
    const wb: XLSX.WorkBook = XLSX.utils.book_new();
    let ws = XLSX.utils.table_to_sheet(elemTable, {raw: true});
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

    /* save to file */
    XLSX.writeFile(wb, '日数据.xlsx');
  }

  onRemove() {
    this.file = null;
  }

  onUploadDayPower(ev) {
    this.fileDayPower = ev.files;
    this.lossElectricity.importDayPower(this.fileDayPower).then(res => {
      if (res && res.code == '200') {
        alert('导入成功！');
        this.onSearch();
        this.onRemoveDayPower();
      } else {
        this.onRemoveDayPower();
        alert('导入失败');
      }
    }).catch(err => {
      this.onRemoveDayPower();
      alert('导入异常');
    });
  }

  onRemoveDayPower() {
    this.fileDayPower = null;
  }

  onUploadOther(ev) {
    this.fileOther = ev.files;
    this.lossElectricity.importOtherBattery(this.fileOther)
      .then(res => {
        if (res && res.code == '200') {
          alert('导入成功！');
          this.onSearch();
          this.onRemoveOther();
        } else {
          alert('导入失败');
        }
      }).catch(err => {
      alert('导入失败');
    });

  }

  onRemoveOther() {
    this.fileOther = null;
  }

  onUploadSpeed(ev) {
    this.fileSpeed = ev.files;
    this.lossElectricity.importAvgwindspeed(this.fileSpeed)
      .then(res => {
        if (res && res.code == '200') {
          alert('导入成功！');
          this.onRemoveSpeed();
        } else {
          alert('导入失败');
        }
      }).catch(err => {
      alert('导入失败');
    });

  }

  onRemoveSpeed() {
    this.fileSpeed = null;
  }

  export(active, id, title) {
    let str = '';
    const fomat = 'yyyy.MM.dd';
    if (active) {
      str = ` 
    <thead >
      <tr>
      <th>${title}</th>
      </tr>
    </thead>
    <thead>
      <tr>
        <th>风场</th>
        <th>工期</th>
        <th>值(kwh)</th>
        <th>电量类型</th>
        <th>时间</th>
        <th>时间类型</th>
      </tr>
    </thead>
    <tbody>`;
      this.rPowers.forEach(rpower => {
        let plantType = '';
        let date = '';
        if (rpower.dateType == 1) {
          date = this.datePipe.transform(rpower.date, fomat)
          plantType = '日';
        } else if (rpower.dateType == 2) {
          date = this.datePipe.transform(rpower.date, fomat)
          plantType = '月';
        }
        else if (rpower.dateType == 3) {
          date = this.datePipe.transform(rpower.date, fomat)
          plantType = '年';
        }
        str += `<tr >
        <td>${rpower.farmName}</td>
        <td>${rpower.phaseName}</td>
        <td>${rpower.value}</td>
        <td>${rpower.powerName}</td>
        <td>${date}</td>
        <td>${plantType}</td>
        
      </tr>`;
      });
    } else {
      str = `
    <thead >
      <tr>
      <th>${title}</th>
      </tr>
    </thead>
    <thead>
      <tr>
      <th>风场</th>
      <th>工期</th>
      <th>风机</th>
      <th>值(kwh)</th>
      <th>时间</th>
      <th>时间类型</th>
      </tr>
    </thead>
    <tbody>`;
      this.rPowers.forEach(rpower => {
        let plantType = '';
        let date = '';
        if (rpower.dateType == 1) {
          date = this.datePipe.transform(rpower.date, fomat)
          plantType = '日';
        } else if (rpower.dateType == 2) {
          date = this.datePipe.transform(rpower.date, fomat)
          plantType = '月';
        }
        else if (rpower.dateType == 3) {
          date = this.datePipe.transform(rpower.date, fomat)
          plantType = '年';
        }
        str += `<tr >
      <td>${rpower.farmName}</td>
      <td>${rpower.phaseName}</td>
      <td>${rpower.deviceName ? rpower.deviceName : ''}</td>
      <td>${rpower.value}</td>
      <td>${date}</td>
      <td>${plantType}</td>
      
    </tr>`;
      });
    }
    /* start = this.datePipe.transform(this.startTime, fomat),
    end = this.datePipe.transform(this.endTime, fomat); */

    str += `</tbody>`;
    const elemTable = document.createElement('table');
    elemTable.innerHTML = str;
    const wb: XLSX.WorkBook = XLSX.utils.book_new();
    var ws = XLSX.utils.table_to_sheet(elemTable);
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

    /* save to file */
    XLSX.writeFile(wb, title + '.xlsx');
  }

  exportData(active, id) {
    let title = '发电量';
    if (active) {
      title = '其他电量'
    }
    this.confirmation.confirm({
      header: '提示信息',
      message: `是否导出${title}电量?`,
      accept: () => {
        this.export(active, id, title);
      },
      reject: () => {

      }

    });

  }

  /* save() {
    const rpower = new Rpower(0, 0, 0, 0, 0, new Date());
    // tslint:disable-next-line:forin
    for (let prop in this.currentRpower) {
      rpower[prop] = this.currentRpower[prop];
    }
    rpower.value = this.changeValue;
    this.lossElectricity.update(rpower)
      .then(res => {
        this.displayDialog = false;
        this.onSearch();
        console.log("updata");
      });
  } */
}

interface SelectOption {
  label: string;
  value: string;
  code?: string;
  keyValue?: string;
}
